# -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 12:12:24 2014

@author: nicolas
"""

import PyNUT
import sys
import time
import pickle
import numpy as np


def saveobject(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)


def readobject(filename):
    with open(filename, 'rb') as infile:
        return pickle.load(infile)
        
        
def logdatas(resultlog,resultarray):
    result = nut.GetUPSVars('ETX1500-test')
    resultlog.append(result)
    resultarray=np.vstack((resultarray,
    list(map(float,[time.time(),result['ups.power'],result['ups.load'],
    result['battery.charge'],result['output.current']]))))
    return result['battery.charge'],resultlog,resultarray


#delays definitions        
delay=1
measdelay=5


if __name__ == "__main__" :
        print( "PyNUT connecty to UPS..." )
        nut    = PyNUT.PyNUTClient( host='raspionduleurs', port=3493 ,login="admin", password="pass", debug=True )
        # demarre la charge
        nut.RunUPSCommand( 'ETX1500-test', "outlet.1.load.on" )
        time.sleep(delay)
        result = nut.GetUPSVars('ETX1500-test')
        rembatt=result['battery.charge']
        resultlog=[]
        resultarray=list(map(float,[time.time(),result['ups.power'],result['ups.load'],
                                    result['battery.charge'],result['output.current']]))
        try:
            print "discharging..."
            while int(rembatt)>85 :
                rembatt,resultlog,resultarray=logdatas(resultlog,resultarray)
                print rembatt
                time.sleep(measdelay)
            print('end of discharge ...')   
        except KeyboardInterrupt:
            print('discharge ended by user ...')
            pass
        
       
        
        #log recharge 
        nut.RunUPSCommand( 'ETX1500-test', "outlet.1.load.off" )
        try:
            print "charging..."
            while int(rembatt)<99 :
                rembatt,resultlog,resultarray=logdatas(resultlog,resultarray)
                print rembatt
                time.sleep(measdelay)
        except KeyboardInterrupt:
            # do nothing here
            print('capture ended by user ...')
            pass

        #        arrete la charge
        
        time.sleep(delay)
        result = nut.GetUPSVars('ETX1500-test')
        print result['ups.power']
        print result['ups.load']
        saveobject(resultlog,'resultlog.pk')
        saveobject(resultarray,'resultarray.pk')
        #plot(resultarray[:,0]-resultarray[0,0],resultarray[:,1:])